package com.zhoujie.roomdemo;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textfield.MaterialAutoCompleteTextView;
import com.google.android.material.textfield.TextInputLayout;
import com.zhoujie.roomdemo.presenter.impl.LoginPresenterImpl;
import com.zhoujie.roomdemo.view.ILoginCallback;

import java.util.List;

public class LoginActivity extends AppCompatActivity implements ILoginCallback {

    private LoginPresenterImpl mPresenter;

    private TextInputLayout pwdLayout;
    private MaterialAutoCompleteTextView autoAccount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        mPresenter = new LoginPresenterImpl();
        mPresenter.registerCallback(this);
        pwdLayout = findViewById(R.id.login_pwd);
        autoAccount = findViewById(R.id.auto_account);

        findViewById(R.id.btn_login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String account = autoAccount.getText().toString();
                if (pwdLayout.getEditText() != null) {
                    String pwd = pwdLayout.getEditText().getText().toString();
                    mPresenter.login(account, pwd);
                }
            }
        });
    }

    @Override
    public void onAutoCompleteTextGet(final List<String> list) {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
        autoAccount.setAdapter(adapter);

        autoAccount.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String account = list.get(position);
                mPresenter.getPwdByAccount(account);
            }
        });
    }

    @Override
    public void onClickAutoAccount(String pwd) {
        if (pwdLayout.getEditText() != null) {
            pwdLayout.getEditText().setText(pwd);
        }
    }

    @Override
    public void onSuccess() {
        Log.d("登录", "onSuccess: ");
    }

    @Override
    public void onError(String errorMsg) {

    }

    @Override
    public void onLoading() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.unregisterCallback(this);
    }
}
